package com.ls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.base.BaseResult;
import com.ls.base.BaseResultUtil;
import com.ls.controller.model.serviceChannel.AddServiceChannelModel;
import com.ls.controller.model.serviceChannel.QueryServiceChannelModel;
import com.ls.controller.model.serviceChannel.UpDownServiceChannelModel;
import com.ls.entity.*;
import com.ls.exception.SysException;
import com.ls.mapper.CommServiceChannelMapper;
import com.ls.service.ICommServiceChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.ls.base.BaseResultUtil.PARAM_LACK;
import static com.ls.base.BaseResultUtil.SQL_ERROR;
import static com.ls.controller.model.serviceChannel.UpDownServiceChannelModel.UP_SERVICE_CHANNEL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2019-12-05
 */
@Service
public class CommServiceChannelServiceImpl extends ServiceImpl<CommServiceChannelMapper, CommServiceChannel> implements ICommServiceChannelService {

    @Autowired
    CommServiceChannelMapper mapper;

    @Override
    public BaseResult add(AddServiceChannelModel model, SysUser currentUser) {
        Long serviceId = model.getServiceId();
        boolean checkFlag = checkServiceChannelExist(serviceId,model.getChanId());
        if (checkFlag) {
            return BaseResultUtil.error("业务与通道绑定关系已存在");
        }
        CommServiceChannel serviceChannel = new CommServiceChannel();
        BeanUtils.copyProperties(model, serviceChannel);
        int serialNo = getSerialNo(serviceId);
        serviceChannel.setSerialNo(serialNo);
        serviceChannel.setCreateTime(LocalDateTime.now());
        serviceChannel.setCreateUserId(currentUser.getUserId());
        serviceChannel.setUpdateTime(LocalDateTime.now());
        serviceChannel.setUpdateUserId(currentUser.getUserId());
        int result = mapper.insert(serviceChannel);
        if (result > 0) {
            return BaseResultUtil.success();
        } else {
            return BaseResultUtil.error(SQL_ERROR);
        }
    }

    private int getSerialNo(Long serviceId) {
        Integer nowMaxSerialNo =mapper.selectCount(new QueryWrapper<CommServiceChannel>().eq("service_id",serviceId));
        if(nowMaxSerialNo==null){
            return 1;
        }else{
            return nowMaxSerialNo + 1;
        }
    }


    @Override
    public boolean checkServiceChannelExist(Long serviceId, Long chanId) {
        CommServiceChannel serviceChannel = mapper.selectOne(new QueryWrapper<CommServiceChannel>().eq("serviceId", serviceId).eq("chan_id",chanId));
        if (serviceChannel == null) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public BaseResult listByPage(QueryServiceChannelModel model, SysUser currentUser) {
        if(model == null ){
            return BaseResultUtil.error(PARAM_LACK);
        }
        Long serviceId = model.getServiceId();
        if(serviceId == null ){
            return BaseResultUtil.error(PARAM_LACK + " serviceId");
        }
        QueryWrapper<CommServiceChannel> wrapper = new QueryWrapper<CommServiceChannel>().eq("service_id",serviceId).orderByAsc(true,"serial_no");
        IPage<CommServiceChannel> pageData = mapper.selectPage(new Page<>(model.getPageNum(), model.getPageSize()), wrapper);
        return BaseResultUtil.success(pageData);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = SysException.class)
    @Override
    public BaseResult upDown(UpDownServiceChannelModel model, SysUser currentUser) {
        Long serChalId = model.getSerChalId();
        CommServiceChannel serviceChannel = mapper.selectById(serChalId);
        if(serviceChannel ==null){
            return BaseResultUtil.error("serChalId: "+serChalId+" 不在库里");
        }
        Integer serialNo = serviceChannel.getSerialNo();
        if(serialNo ==null || serialNo<0){
            return BaseResultUtil.error("serialNo: "+serChalId+" serialNo:"+serialNo+" 数据错误");
        }
        Long serviceId = serviceChannel.getServiceId();
//        QueryWrapper<CommServiceChannel> wrapper = new QueryWrapper<CommServiceChannel>().eq("service_id",serviceId).orderByAsc(true,"serial_no");
//        List<CommServiceChannel> serviceChannelList = mapper.selectList(wrapper);
//        if(serviceChannelList.size() == 1){
//            return BaseResultUtil.error("只有一条数据，无需上移下移");
//        }
        int upDown = model.getUpDown();
        QueryWrapper<CommServiceChannel> wrapper = new QueryWrapper<CommServiceChannel>().eq("service_id",serviceId);
        if (upDown == UP_SERVICE_CHANNEL){
            wrapper.eq("serial_no",serialNo - 1);
        }else{
            wrapper.eq("serial_no",serialNo + 1);
        }
        CommServiceChannel  serviceChannelToSwap= mapper.selectOne(wrapper);
        if(serviceChannelToSwap ==null){
            return BaseResultUtil.error("无需上移下移");
        }
        Integer serialNoToSwap= serviceChannelToSwap.getSerialNo();
        serviceChannel.setSerialNo(serialNoToSwap);
        serviceChannelToSwap.setSerialNo(serialNo);
        mapper.updateById(serviceChannel);
        mapper.updateById(serviceChannelToSwap);
        return BaseResultUtil.success();
    }

}
